using System;
using System.Net;
using System.Net.Sockets;

namespace Framework.Library.Core.Utils.Miscellaneous
{
    public class UdpClientDataGetter : IDataGetter
    {
        private int _port;
        private UdpClient _udpClient;

        public UdpClientDataGetter(int port)
        {
            _port = port;
        }

        public int Port
        {
            get { return _port; }
            set { _port = value; }
        }

        #region IDataGetter Members

        public byte[] GetData()
        {
            if (_udpClient == null)
                _udpClient = new UdpClient(_port);

            // I don't know why remoteEP parameter on Receive is ref
            // default this to null
            IPEndPoint remoteEndPoint = null;

            try
            {
                return _udpClient.Receive(ref remoteEndPoint);
            }
            catch (SocketException e)
            {
                // an exception will get thrown if UdpClient is waiting 
                // on receive and is closed
                if (e.SocketErrorCode == SocketError.Interrupted)
                    return null;
                else
                    throw;
            }
        }

        void IDisposable.Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        #endregion

        private void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (_udpClient != null)
                    _udpClient.Close();
            }
        }

        ~UdpClientDataGetter()
        {
            Dispose(false);
        }
    }
}